using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.ErrorCode;
using RBAC.Interstructrue;
using RBAC.Write.Api.Application.Command.ERP.SalesManagement.Billing;

namespace RBAC.Write.Api.Application.Handler.ERP.SalesManagement.Billing
{
    /// <summary>
    /// 审核开票通知单处理器
    /// </summary>
    public class AuditBillingNoticeHandler : IRequestHandler<AuditBillingNoticeCommand, APIResult<bool>>
    {
        private readonly RBACDbContext _context;
        private readonly ILogger<AuditBillingNoticeHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">数据库上下文</param>
        /// <param name="logger">日志记录器</param>
        public AuditBillingNoticeHandler(RBACDbContext context, ILogger<AuditBillingNoticeHandler> logger)
        {
            _context = context;
            _logger = logger;
        }

        /// <summary>
        /// 处理审核开票通知单请求
        /// </summary>
        /// <param name="request">审核命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>审核结果</returns>
        public async Task<APIResult<bool>> Handle(AuditBillingNoticeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查找开票通知单
                var billingNotice = await _context.BillingAccountings
                    .FirstOrDefaultAsync(b => b.BillNumber == request.BillNumber && !b.IsDeleted, cancellationToken);

                if (billingNotice == null)
                {
                    return new APIResult<bool>
                    {
                        Code = APIEnums.Fail,
                        Msg = "未找到指定的开票通知单"
                    };
                }

                // 检查是否已审核
                if (billingNotice.Status == 1)
                {
                    return new APIResult<bool>
                    {
                        Code = APIEnums.Fail,
                        Msg = "该开票通知单已审核，无需重复审核"
                    };
                }

                // 检查是否为退回状态，退回状态也可以重新审核
                if (billingNotice.Status == 2)
                {
                    // 退回状态可以重新审核，继续执行
                }

                // 更新状态为审核（使用中文状态名：审核）
            billingNotice.Status = 1; // 1=审核
            billingNotice.BillStatus = "审核";
                billingNotice.ReviewDate = DateTime.Now;
                billingNotice.Reviewer = request.Operator;

                await _context.SaveChangesAsync(cancellationToken);

                return new APIResult<bool>
                {
                    Code = APIEnums.Success,
                    Msg = "开票通知单审核成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "审核开票通知单时发生异常");
                return new APIResult<bool>
                {
                    Code = APIEnums.Fail,
                    Msg = "审核失败：" + ex.Message,
                    Data = false
                };
            }
        }
    }
}